document.addEventListener('DOMContentLoaded', function() {
    const sidebar = document.getElementById('sidebar');
    const resizer = document.getElementById('resizer');
    const refreshBtn = document.getElementById('refresh-btn');
    const issueListContainer = document.getElementById('issue-list-container');
    const mainContent = document.getElementById('main-content');
    const welcomePanel = document.getElementById('welcome');
    const logsContainer = document.getElementById('logs-container');
    const logsContent = document.getElementById('logs-content');

    // --- Store all issues globally to build detail views ---
    let allIssues = [];
    let eventSource = null;

    // --- Main Function to Connect and Stream Data ---
    function connectAndStream() {
        if (eventSource) {
            eventSource.close();
        }

        console.log('Connecting to stream...');
        refreshBtn.classList.add('loading');
        refreshBtn.disabled = true;

        // Clear previous content and show logs
        logsContent.innerHTML = '';
        logsContainer.style.display = 'block';
        welcomePanel.classList.remove('active');
        // Corrected selector: Do NOT remove the #welcome panel itself.
        mainContent.querySelectorAll('.issue-detail:not(#welcome)').forEach(el => el.remove());


        eventSource = new EventSource('/stream-updates');

        eventSource.addEventListener('log', function(e) {
            const logLine = document.createElement('div');
            logLine.textContent = e.data;
            logsContent.appendChild(logLine);
            logsContent.scrollTop = logsContent.scrollHeight; // Auto-scroll
        });

        eventSource.addEventListener('data', function(e) {
            console.log('Data received, rendering content...');
            const data = JSON.parse(e.data);

            // Hide logs and show content
            logsContainer.style.display = 'none';
            
            allIssues = [];
            renderSidebar(data);
            renderMainContent(data);
            
            // After rendering, ensure the welcome panel is visible until an issue is clicked.
            welcomePanel.classList.add('active');

            // We are done, close the connection
            eventSource.close();
            refreshBtn.classList.remove('loading');
            refreshBtn.disabled = false;
        });

        eventSource.onerror = function(e) {
            console.error('EventSource failed:', e);
            const errorLine = document.createElement('div');
            errorLine.className = 'error';
            errorLine.textContent = '与服务器的连接已断开。请刷新页面重试。';
            logsContent.appendChild(errorLine);
            logsContent.scrollTop = logsContent.scrollHeight;

            eventSource.close();
            refreshBtn.classList.remove('loading');
            refreshBtn.disabled = false;
        };
    }

    // --- Main Function to Fetch and Render Data ---
    async function fetchAndRenderIssues() {
        console.log('Fetching issues...');
        refreshBtn.classList.add('loading');
        
        // For initial load, the HTML already has a "loading" message.
        // For refresh clicks, we will NOT clear the UI until data is ready.

        try {
            const response = await fetch('/api/issues');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            
            // --- We have the new data, NOW we can clear the old UI ---
            issueListContainer.innerHTML = ''; 
            mainContent.innerHTML = ''; 
            mainContent.appendChild(welcomePanel); 
            welcomePanel.classList.add('active');

            // Reset global issue store and render new content
            allIssues = [];
            renderSidebar(data);
            renderMainContent(data);

        } catch (error) {
            console.error('Fetch error:', error);
            issueListContainer.innerHTML = `<div class="loader" style="color: red;">获取数据失败！<br>${error.message}</div>`;
            mainContent.innerHTML = ''; // Clear main content on error too
            mainContent.appendChild(welcomePanel); 
            welcomePanel.classList.add('active');
        } finally {
            refreshBtn.classList.remove('loading');
        }
    }

    function renderSidebar(categorizedData) {
        let sidebarHtml = '';
        const priority_order = ['P0', 'P1', 'P2', 'P3', '无优先级'];

        let totalIssues = 0;
        priority_order.forEach(priority => {
            const issuesInCategory = categorizedData[priority] || [];
            totalIssues += issuesInCategory.length;

            if (issuesInCategory.length > 0) {
                sidebarHtml += `
                <details class="priority-group" open>
                    <summary>${priority} (${issuesInCategory.length} 个)</summary>
                    <ul class="issue-list">
                        ${issuesInCategory.map(issue => `
                            <li class="issue-list-item">
                                <a href="#" data-target="issue-${issue.id}">#${issue.iid} - ${escapeHtml(issue.title)}</a>
                            </li>
                        `).join('')}
                    </ul>
                </details>
                `;
            }
        });

        issueListContainer.innerHTML = sidebarHtml;
        document.querySelector('#sidebar-header h2').textContent = `问题列表 (${totalIssues})`;
    }

    function renderMainContent(categorizedData) {
        let detailsHtml = '';
        const priority_order = ['P0', 'P1', 'P2', 'P3', '无优先级'];

        // Collect all issues from categories into a single array
        priority_order.forEach(priority => {
            const issuesInCategory = categorizedData[priority] || [];
            allIssues.push(...issuesInCategory);
        });

        allIssues.forEach(issue => {
            // Very basic markdown to HTML for bold and lists
            // let descriptionHtml = escapeHtml(issue.description);
            // Naive markdown links: [text](url) -> <a href="url">text</a>
            // descriptionHtml = descriptionHtml.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
             // Naive bold: **text** -> <strong>text</strong>
            // descriptionHtml = descriptionHtml.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>');
            const descriptionHtml = issue.description; // The server now sends ready-to-use HTML

            detailsHtml += `
            <div id="issue-${issue.id}" class="issue-detail">
                <h1>#${issue.iid} - ${escapeHtml(issue.title)}</h1>
                <div class="meta-info">
                    <div class="meta-item"><strong>负责人:</strong> ${escapeHtml(issue.assignee)}</div>
                    <div class="meta-item"><strong>报告人:</strong> ${escapeHtml(issue.author)}</div>
                    <div class="meta-item"><strong>状态:</strong> ${escapeHtml(issue.state)}</div>
                    <div class="meta-item"><strong>标签:</strong> ${issue.labels.join(', ') || '无'}</div>
                    <div class="meta-item"><strong>创建于:</strong> ${issue.created_at}</div>
                    <div class="meta-item"><strong>更新于:</strong> ${issue.updated_at}</div>
                    <div class="meta-item"><strong>链接:</strong> <a href="${issue.web_url}" target="_blank">在 GitLab 中打开</a></div>
                </div>
                <div class="description">
                    <h3>问题描述</h3>
                    <div class="description-content">${descriptionHtml || "无描述。"}</div>
                </div>
            </div>
            `;
        });
        
        // Append new details to main content, after the welcome message
        welcomePanel.insertAdjacentHTML('afterend', detailsHtml);
    }
    
    function escapeHtml(str) {
        return str
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
    }


    // --- Event Listeners ---
    refreshBtn.addEventListener('click', connectAndStream);

    // Event delegation for issue links
    issueListContainer.addEventListener('click', function(e) {
        if (e.target.tagName === 'A') {
            e.preventDefault();
            const targetId = e.target.getAttribute('data-target');
            
            // Hide logs and welcome message when an issue is selected
            logsContainer.style.display = 'none';
            welcomePanel.classList.remove('active');

            document.querySelectorAll('.issue-detail').forEach(detail => detail.classList.remove('active'));
            document.getElementById(targetId).classList.add('active');
            
            document.querySelectorAll('.issue-list-item a').forEach(l => l.classList.remove('active'));
            e.target.classList.add('active');
        }
    });

    // Resizer Logic
    let isResizing = false;
    resizer.addEventListener('mousedown', function(e) {
        isResizing = true;
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', stopResize);
    });

    function handleMouseMove(e) {
        if (!isResizing) return;
        const newWidth = e.clientX;
        if (newWidth > 250 && newWidth < (window.innerWidth - 250)) {
            sidebar.style.flexBasis = newWidth + 'px';
        }
    }

    function stopResize() {
        isResizing = false;
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', stopResize);
    }

    // Lightbox Logic
    const lightboxOverlay = document.getElementById('lightbox-overlay');
    const lightboxImage = document.getElementById('lightbox-image');
    const lightboxClose = document.getElementById('lightbox-close');

    mainContent.addEventListener('click', function(e) {
        if (e.target.tagName === 'IMG') {
            lightboxImage.src = e.target.src;
            lightboxOverlay.style.display = 'flex';
        }
    });

    function closeLightbox() {
        lightboxOverlay.style.display = 'none';
        lightboxImage.src = '';
    }

    lightboxClose.addEventListener('click', closeLightbox);
    lightboxOverlay.addEventListener('click', e => e.target === lightboxOverlay && closeLightbox());
    document.addEventListener('keydown', e => e.key === 'Escape' && closeLightbox());

    // --- Initial Load ---
    connectAndStream();
}); 